<?php

ini_set("display_errors", true);

	function escapeHTML($value) 
	{
		return htmlspecialchars($value,ENT_QUOTES,'UTF-8');
	}
/*
	 * The supported privs will be displayed as a tree of checkboxes, 
	 * with abstract privileges grayed.
	 */
	function appendSP($spaces, $appendTo, $privName, $inner)
	{
		$description = $inner["description"];
		if (!$inner["abstract"])
		{
			$appendTo .= "$spaces<input type='checkbox' value=\"$privName\"> $privName $description<br />\n";
		}
		if (isset($inner["container"]))
		{
			foreach ($inner["container"] as $privName=>$inner)
			{
				$this->appendSP($spaces . "&nbsp;", &$appendTo, $privName, $inner);
			}
		} else {
			$container = null;
		}		
	}

	function generatePage($server)
	{
		$path = $server->httpRequest->getUri();
		$parts = explode("/", $path);
		unset($parts[count($parts)-1]);
		$path = $server->getBaseUri() . implode("/", $parts);
		print $path;
		
		$files = $server->getPropertiesForPath($path,array(
        '{DAV:}resourcetype',
        '{DAV:}getcontenttype',
        '{DAV:}getcontentlength',
        '{DAV:}getlastmodified',
        '{DAV:}acl',
				"{DAV:}supported-privilege-set",
				"{DAV:}owner"
				),1);
		
		$fileHtml = "";
		//var_dump($files);
		$aceData = "";
		$princs = $server->getAllPrincipals();
		
		//selpData is data for the Principal select element.
		$selpData = array();
		foreach ($princs as $princ)
		{
			$name = $princ->getName();
			$uri = $princ->getUri();
			$selpData[] = array("uri"=>"href:$uri", "name"=>$name);
		}
		$selpData[] = array("uri"=>"authenticated:", "name"=>"authenticated");
		$selpData[] = array("uri"=>"unauthenticated:", "name"=>"unauthenticated");
		$selpData[] = array("uri"=>"self:", "name"=>"self");
		$selpData[] = array("uri"=>"all:", "name"=>"all");
		$selpData[] = array("uri"=>"property:{DAV:}owner", "name"=>"owner");
		$selp="";
		$spsData = "";
		$privData = "";
		foreach($files as $k=>$file) 
		{
			//$aceData .= $file["href"];
			// This is the current directory, we can skip it
			if (rtrim($file['href'],'/')==$path)
			{
				//$aceData .= "Found the current directory<br />";

				$owner = $file[200]["{DAV:}owner"]->getHref();
				$selOwnerData = array() + $selpData;
				$selOwner = "<select name=\"selo\">";
				foreach ($selOwnerData as $ownerData)
				{
					$uri = $ownerData["uri"];
					$name = $ownerData["name"];
					if ($uri == "href:$owner")
					{
						$selOwner .= ("<option selected='true' value=\"$uri\">$name</option>\n");
					} else {
						$selOwner .= ("<option value=\"$uri\">$name</option>\n");
					}
				}
				$selOwner .= "</select>\n";
				
				if (isset($file[200]["{DAV:}acl"]))
				{
					$acl = $file[200]["{DAV:}acl"];
					$sps = $file[200]["{DAV:}supported-privilege-set"];
					$aces = $acl->getAces();
					foreach ($aces as $princStr=>$ace)
					{
						//You could have (e.g.) grant all, deny write, grant write-content for a single principal.
						foreach ($ace as $aceAction)
						{
							$aceData .= "<tr>";
							$aceData .= "<td>$princStr</td>";
							$p = $aceAction["protected"]?"P":"U";
							$g = $aceAction["grant"]?"G":"D";
							$aceData .= "<td>$p</td>";
							$aceData .= "<td>$g</td>";
							$aceData .= "<td>";
							foreach ($aceAction["privs"] as $priv)
							{
								$aceData .= "$priv ";
							}
							$aceData .= "</td></tr>\n";
						}
					}
					$aceData .= "</table>";
					$spsData = "<form>";
					$privileges = $sps->getPrivileges();
					foreach ($privileges as $privname=>$inner)
					{
						appendSP("", &$spsData, $privname, $inner);
					}
					$spsData .= "</form>";
				}				
			} else {
				list(, $name) = Sabre_DAV_URLUtil::splitPath($file['href']);
				$name = escapeHTML($name);
	
				$type = null;
				if (isset($file[200]['{DAV:}resourcetype'])) 
				{
					$type = $file[200]['{DAV:}resourcetype']->getValue();
					// resourcetype can have multiple values
					if (is_array($type)) 
					{
						$type = implode(', ', $type);
					}
	
					// Some name mapping is preferred
					switch($type) 
					{
						case '{DAV:}collection' :
							$type = 'Collection';
							break;
					}
				}
	
				// If no resourcetype was found, we attempt to use
				// the contenttype property
				if (!$type && isset($file[200]['{DAV:}getcontenttype'])) 
				{
					$type = $file[200]['{DAV:}getcontenttype'];
				}
				if (!$type) 
				{
					$type = 'Unknown';
				}
	
				$type = escapeHTML($type);
				$size = isset($file[200]['{DAV:}getcontentlength'])?(int)$file[200]['{DAV:}getcontentlength']:'';
				$lastmodified = isset($file[200]['{DAV:}getlastmodified'])?$file[200]['{DAV:}getlastmodified']->getTime()->format(DateTime::ATOM):'';
	
				$fullPath = Sabre_DAV_URLUtil::encodePath('/' . trim($server->getBaseUri() . ($path?$path . '/':'') . $name,'/'));
	
				$fileHtml.= "<tr>
	<td><a href=\"{$fullPath}\">{$name}</a></td>
	<td>{$type}</td>
	<td>{$size}</td>
	<td>{$lastmodified}</td>
	</tr>";
			}

		}
		$dirname = escapeHTML($path);
		ob_start();
		include "dirIndex.php";
		$html = ob_get_clean();
		return $html;

	}

	
require_once 'autoload.php';
require_once 'Sabre/autoload.php';

	
$server = Slash_CalDAV_Server::getInstance();
print generatePage($server);
?>

